﻿using System;
using System.Collections.Generic;
using System.Linq;
using BaseRepository.Db.UnitOfWork;
using Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Extensions.Services;

public static class AddEFCore
{
   // 通过泛型传进来dbcontext来注册
    public static IServiceCollection AddEFCoreSetup<T>(this IServiceCollection services) where T : DbContext
    {
        if (services == null) throw new ArgumentNullException(nameof(services));

        var sqlConfig = Appsettings.app<List<SqlConfig>>("Sql");
        ArgumentNullException.ThrowIfNull(sqlConfig);
        var sqlServer = sqlConfig.FirstOrDefault(p => p.Name == "sqlserver" && p.Enable);
        var mysql = sqlConfig.FirstOrDefault(p => p.Name == "mysql" && p.Enable);
        if (sqlConfig.Count(p => p.Enable)>1)
        {
            throw new Exception("只能配置一个数据库连接为enable,请检查配置！");
        }
        else if (sqlServer!=null)
        {
            services.AddDbContext<T>(options =>
            {
                options.UseSqlServer(sqlServer.ConnectionString);
                
            });
        }
        else if (mysql!=null)
        {
            services.AddDbContext<T>(options =>
            {
                options.UseMySql(mysql.ConnectionString, ServerVersion.AutoDetect(mysql.ConnectionString));
            });
        }
        else
        {
            throw new Exception("connectionString配置错误，请检查");
        }

        // 工作单元  在这边注入
        // 一个服务只支持一个工作单元  
        services.AddScoped<IUnitOfWork, UnitOfWork<T>>();
        return services;
    }
    /// <summary>
    /// sql配置文件
    /// </summary>
    public class SqlConfig
    {
        /// <summary>
        /// 数据库名称
        /// </summary>
        public string? Name { get; set; }
        /// <summary>
        /// 连接字符串
        /// </summary>
        public string? ConnectionString { get; set; }
        /// <summary>
        /// 是否启用
        /// </summary>
        public bool Enable { get; set; }

    }

}